package com.dev.security.shiro;

import com.dev.security.util.ResponseUtil;
import com.dev.security.vo.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录过滤器
 *
 * @ Author：across-cai
 * @ Time：2020/4/18 16:04
 * @ Motto：我只想做你的太阳
 */
@Slf4j
public class LoginFilter extends FormAuthenticationFilter {
    /**
     * 认证失败
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;
        boolean ajaxRequest = isAjaxRequest(req);

        if (ajaxRequest){
            log.info(req.getRequestURI() + " isAjax 请求");
            ResponseData responseData = new ResponseData();
            responseData.setCode(100);
            responseData.setMessage("登录认证失败");
            //将信息写到前台
            ResponseUtil.writeJson(resp,responseData);
        }else {
            //重定向登录
            saveRequestAndRedirectToLogin(request,response);
        }

        return false;
    }

    /**
     * 判断一个请求是否是ajax请求，是则返回true
     */
    public static boolean isAjaxRequest(HttpServletRequest request){
        String requestType = request.getHeader("X-Requested-With");

        if (requestType == null){
            return false;
        }

        return true;
    }
}
